package com.match.competition_role.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.commonutils.Result;
import com.match.competition_role.client.RoleClient;
import com.match.competition_role.entity.CompetitionRole;
import com.match.competition_role.entity.CompetitionUserRole;
import com.match.competition_role.entity.lever.OneSubject;
import com.match.competition_role.entity.lever.TwoSubject;
import com.match.competition_role.entity.vo.TeaQuery;
import com.match.competition_role.service.CompetitionRoleService;
import com.match.competition_role.service.CompetitionUserRoleService;
import com.match.entity.Vo.UserRoleVo;
import com.match.entity.baseEntity.Teacher;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AdiosF
 * @since 2021-10-02
 */
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/admin/competition_role/competition-user")
public class CompetitionUserController {
    @Autowired
    private CompetitionUserRoleService competitionUserRoleService;
    @Autowired
    private RoleClient roleClient;
    @Autowired
    private CompetitionRoleService competitionRoleService;



    @ApiOperation("为教师添加角色")
    @PostMapping("/userAddRole")
    public Result userAddRole(@ApiParam(required = true)
                              @RequestBody com.match.competition_role.entity.vo.UserRoleVo userRoleVo){
        List<String> teacherNumberList = userRoleVo.getTeacherNumberList();
        for (String s : teacherNumberList) {
            //查重
            QueryWrapper<CompetitionUserRole> competitionUserRoleQueryWrapper=new QueryWrapper<>();
            competitionUserRoleQueryWrapper.eq("user_id",s);
            CompetitionUserRole one = competitionUserRoleService.getOne(competitionUserRoleQueryWrapper);
            if (!StringUtils.isEmpty(one)){
                competitionUserRoleService.remove(competitionUserRoleQueryWrapper);
                //1.首先向中间表添加数据
                CompetitionUserRole competitionUserRole=new CompetitionUserRole();
                competitionUserRole.setUserId(s);
                competitionUserRole.setRoleId(userRoleVo.getRoleId());
                competitionUserRoleService.save(competitionUserRole);

                CompetitionRole byId = competitionRoleService.getById(userRoleVo.getRoleId());
                com.match.entity.Vo.UserRoleVo userRoleVo1= new com.match.entity.Vo.UserRoleVo();
                //setRoleId为角色名称
                userRoleVo1.setRoleId(byId.getRoleName());
                userRoleVo1.setTeacherNumber(s);
                roleClient.updateUserRoleByNumber(userRoleVo1);
            }else {
                //1.首先向中间表添加数据
                CompetitionUserRole competitionUserRole=new CompetitionUserRole();
                competitionUserRole.setUserId(s);
                competitionUserRole.setRoleId(userRoleVo.getRoleId());
                competitionUserRoleService.save(competitionUserRole);

                CompetitionRole byId = competitionRoleService.getById(userRoleVo.getRoleId());
                com.match.entity.Vo.UserRoleVo userRoleVo1= new com.match.entity.Vo.UserRoleVo();
                //setRoleId为角色名称
                userRoleVo1.setRoleId(byId.getRoleName());
                userRoleVo1.setTeacherNumber(s);
                roleClient.updateUserRoleByNumber(userRoleVo1);
            }
        }
        return Result.ok().message("角色分配成功");
    }


    @ApiOperation("修改教师角色")
    @PostMapping("/updateUserRoleByRoleId")
    public Result updateUserRoleById(@ApiParam(required = true)
                                @RequestBody com.match.entity.Vo.UserRoleVo userRoleVo){
        //查重
        QueryWrapper<CompetitionUserRole> competitionUserRoleQueryWrapper=new QueryWrapper<>();
        competitionUserRoleQueryWrapper.eq("user_id",userRoleVo.getTeacherNumber());
        competitionUserRoleQueryWrapper.eq("role_id",userRoleVo.getRoleId());
        CompetitionUserRole one = competitionUserRoleService.getOne(competitionUserRoleQueryWrapper);
        if (!StringUtils.isEmpty(one)){
            return Result.error().message("不可修改相同的角色");
        }
        //1.修改中间表的数据即可
        CompetitionUserRole competitionUserRole=new CompetitionUserRole();
        competitionUserRole.setUserId(userRoleVo.getTeacherNumber());
        competitionUserRole.setRoleId(userRoleVo.getRoleId());
        QueryWrapper<CompetitionUserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userRoleVo.getTeacherNumber());
        competitionUserRoleService.update(competitionUserRole,queryWrapper);
        //2.修改教师角色
        CompetitionRole byId = competitionRoleService.getById(userRoleVo.getRoleId());
        com.match.entity.Vo.UserRoleVo userRoleVo1= new com.match.entity.Vo.UserRoleVo();
        userRoleVo1.setRoleId(byId.getRoleName());
        userRoleVo1.setTeacherNumber(userRoleVo.getTeacherNumber());
        roleClient.updateUserRoleByNumber(userRoleVo1);
        return Result.ok().message("角色修改成功");
    }


    @ApiOperation("通过服务调用条件查询教师")
    @PostMapping("/getTeacherByQuery")
    public Result getTeacherByQuery(@ApiParam(required = true)
                               @RequestBody TeaQuery teaQuery){
        Map<String, Object> data = roleClient.findTeaByQuery(teaQuery).getData();
        return Result.ok().data("data",data);
    }


    @ApiOperation("通过服务调用得到教师信息")
    @GetMapping("/getTeacherByNumber/{teacherNumber}")
    public Result getTeacherByNumber(@ApiParam(required = true,value = "教师职工号")
                                @PathVariable(value = "teacherNumber")String teacherNumber){
        Result teaByNum = roleClient.getTeaByNum(teacherNumber);
        Map<String, Object> data = teaByNum.getData();
        return Result.ok().data("data",data);
    }


    //TODO
    @ApiOperation("获得所有的角色以及对应的用户")
    @GetMapping("/getAllRoleToTeacher")
    public Result getAllRoleToTeacher(){
        //查询所有角色
        QueryWrapper<CompetitionRole> competitionRoleQueryWrapper=new QueryWrapper<>();
        competitionRoleQueryWrapper.eq("role_name","教师");
        CompetitionRole teacherRole = competitionRoleService.getOne(competitionRoleQueryWrapper);

        //获得所有分配过的用户
        List<String> stringList=new ArrayList<>();
        QueryWrapper<CompetitionUserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.notIn("role_id",teacherRole.getId());
        queryWrapper.select("distinct user_id");
        List<CompetitionUserRole> userList = competitionUserRoleService.list(queryWrapper);
        for (CompetitionUserRole competitionUserRole : userList) {
            stringList.add(competitionUserRole.getUserId());
        }
        Result teacherRoleNotIn = roleClient.getTeacherRoleNotIn(stringList);
        Object list = teacherRoleNotIn.getData().get("list");
        //先将linkedHashMap类型的字符串转化成JSON格式的字符串，再转化成实体类
        String s = JSON.toJSONString(list);
        List<Teacher> teacherList = JSON.parseArray(s, Teacher.class);

        QueryWrapper<CompetitionRole> newCompetitionRoleQueryWrapper=new QueryWrapper<>();
        newCompetitionRoleQueryWrapper.notIn("role_name","教师");
        List<CompetitionRole> roleList = competitionRoleService.list(newCompetitionRoleQueryWrapper);
        //在userAndRole表中查询所有的记录
        List<CompetitionUserRole> allUserRole = competitionUserRoleService.list(null);

        //封装一级目录(角色名称)
        List<OneSubject> finallyList=new ArrayList<>();
        for (CompetitionRole competitionRole : roleList) {
            OneSubject oneSubject=new OneSubject();
            oneSubject.setId(competitionRole.getId());
            oneSubject.setLabel(competitionRole.getRoleName());
            oneSubject.setState("1");
            //遍历所有的二级目录(教师)
            List<TwoSubject> twoSubjectList=new ArrayList<>();
            for (CompetitionUserRole competitionUserRole : allUserRole) {
                if (competitionUserRole.getRoleId().equals(competitionRole.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    twoSubject.setId(competitionUserRole.getUserId());
                    twoSubject.setLabel(getTeacherName(teacherList,competitionUserRole.getUserId()));
                    twoSubject.setState("0");
                    twoSubject.setPId(competitionRole.getId());
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
            finallyList.add(oneSubject);
        }
        return Result.ok().data("list",finallyList);
    }



    @ApiOperation("根据教师职工号删除教师角色")
    @DeleteMapping("/deleteUserRoleByTeacherNumber/{teacherNumber}/{roleId}")
    public Result deleteUserRoleByTeacherNumber(@ApiParam(required = true,value = "教师职工号")
                                           @PathVariable(value = "teacherNumber")String teacherNumber,
                                                @ApiParam(required = true,value = "角色Id")
                                           @PathVariable(value = "roleId")String roleId){
        //根据条件查询教师对应的角色
        QueryWrapper<CompetitionUserRole> competitionUserRoleQueryWrapper=new QueryWrapper<>();
        competitionUserRoleQueryWrapper.eq("user_id",teacherNumber);
        int count = competitionUserRoleService.count(competitionUserRoleQueryWrapper);
        //大于1说明该教师拥有多个角色(只删中间表即可)
        if (count>1){
            competitionUserRoleQueryWrapper.eq("role_id",roleId);
            competitionUserRoleService.remove(competitionUserRoleQueryWrapper);
            return Result.ok();
        }
        //不大于1时说明该用户只有一个角色
        //重新为教师分配教师角色
        com.match.entity.Vo.UserRoleVo userRoleVo=new com.match.entity.Vo.UserRoleVo();
        //roleId这时为角色名称不是角色Id
        userRoleVo.setRoleId("教师");
        userRoleVo.setTeacherNumber(teacherNumber);
        roleClient.updateUserRoleByNumber(userRoleVo);

        //更新教师角色为教师
        QueryWrapper<CompetitionRole> competitionRoleQueryWrapper=new QueryWrapper<>();
        competitionRoleQueryWrapper.eq("role_name","教师");
        CompetitionRole one = competitionRoleService.getOne(competitionRoleQueryWrapper);
        UserRoleVo userRoleVo1=new UserRoleVo();
        userRoleVo1.setRoleId(one.getId());
        userRoleVo1.setTeacherNumber(teacherNumber);
        this.updateUserRoleById(userRoleVo1);
        return Result.ok().message("移除成功");
    }



    /**
     * 得到教师名称姓名
     */
    private String getTeacherName(List<Teacher> list, String number){
        for (Teacher teacher : list) {
            if (teacher.getNumber().equals(number)){
                return teacher.getName();
            }
        }
        return "";
    }
}

